package com.afly.netty.core.codec;

import com.afly.netty.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * <p> 设备信息解码器 </p>
 *
 * @author liuziming
 * @description
 * @date 2023/10/26 15:01
 */
@Slf4j
public class DeviceDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {

        log.info("byteBuf==>{}",in);

        int size = in.readableBytes();
        String datum = ""; //数据位
        byte[] data = new byte[size];
        in.readBytes(data);
        if (data[1] == 68){ //设备发送数据
            datum = Arrays.toString(data);
        } else { //设备启动发送设备id
            String s = new String(data, StandardCharsets.US_ASCII);
            log.info("设备通电发送id===>{}",s);
            out.add(s);
            return;
        }
        log.info("数据位===>{}", datum);
        log.info("hex===>{}", HexUtil.bytes2hex(data));
        log.info("data===>{}",data);
        //String hexMsg = HexUtil.bytes2hex(data);
        String s = String.valueOf(datum);
        out.add(s);
    }

}
